package com.netty.io.netty;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import org.apache.commons.lang3.StringUtils;

import java.time.LocalDateTime;

public class TimeServerHandler extends ChannelHandlerAdapter {


    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        ByteBuf request = (ByteBuf) msg;

        byte[] byteArr = new byte[request.readableBytes()];

        request.readBytes(byteArr);

        String str = new String(byteArr, "UTF-8");

        System.out.println("the time server receive order:" + str);

        String currentTime = StringUtils.equalsIgnoreCase(str,"QUERY TIME ORDER") ? LocalDateTime.now().toString() : "BAD ORDER";

        ByteBuf response = Unpooled.copiedBuffer(currentTime.getBytes());

        ctx.write(response);
    }

    public void channelReadComplete(ChannelHandlerContext ctx){
        ctx.flush();
    }

    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause){
        ctx.close();
    }

}
